package com.youngjun.user.service.impl;

import com.youngjun.user.mapper.AddressMapper;
import com.youngjun.user.pojo.domain.Address;
import com.youngjun.user.pojo.dto.AddressDTO;
import com.youngjun.user.pojo.vo.AddressVO;
import com.youngjun.user.pojo.vo.RegionVO;
import com.youngjun.user.service.AddressService;
import com.youngjun.user.service.RegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AddressServiceImpl implements AddressService {

    @Autowired
    AddressMapper addressMapper;

    @Autowired
    RegionService regionService;

    @Override
    public AddressMapper getMapper() {
        return addressMapper;
    }

    @Override
    public AddressVO queryById(Long addressId) {
        Address address = select(new Address().setId(addressId));
        return transform(address);
    }

    @Override
    public AddressVO create(AddressDTO dto) {
        boolean isEquals=false;
        Address newAddress = new Address().mapFrom(dto);
        if(newAddress.getId() != null ){
            Address oldAddress = select(new Address().setId(newAddress.getId()));
            if(oldAddress != null ){
                isEquals=check(newAddress,oldAddress);
            }
        }
        if(!isEquals){
            newAddress.setId(null);
            if(newAddress.getId() != null ){
                deleteWithLogic(newAddress.getId());
            }
            insert(newAddress);
        }
        return transform(newAddress);
    }

    @Override
    public boolean check(Address newAddress,Address oldAddress) {
        return newAddress.getProvinceId().equals(oldAddress.getProvinceId())
                && newAddress.getCityId().equals(oldAddress.getCityId())
                && newAddress.getDistrictId().equals(oldAddress.getDistrictId())
                && newAddress.getDetailAddress().equals(oldAddress.getDetailAddress());
    }

    @Override
    public AddressVO transform(Address address) {
        AddressVO vo = new AddressVO().mapFrom(address);
        RegionVO province = regionService.queryById(address.getProvinceId());
        vo.setProvinceName(province.getName());
        RegionVO city = regionService.queryById(address.getCityId());
        vo.setCityName(city.getName());
        RegionVO district = regionService.queryById(address.getDistrictId());
        vo.setDistrictName(district.getName());
        return vo;
    }

}